﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Framework;
using WebAppAuthAdmin.AuthApiManagementServiceReference;
using WebAppAuthAdmin.Code;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;
using System.Text;

namespace WebAppAuthAdmin.App
{
    public partial class UserEditRole : BasePage
    {
        private WebApplicationInfo WebApplicationInfo
        {
            get
            {
                return (WebApplicationInfo)this.ViewState["webApp"];
            }
            set
            {
                this.ViewState["webApp"] = value;
            }
        }       

        private AdUser AdUser
        {
            get
            {
                return (AdUser)this.ViewState["AdUser"];
            }
            set
            {
                this.ViewState["AdUser"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton crearContactoButton = new LinkButton();
            crearContactoButton.ID = "guardarButton";
            crearContactoButton.Text = "Guardar";
            crearContactoButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(crearContactoButton);

            base.LoadContextActions(actionButtons);
        }

        protected override void ApplySecurity()
        {
            bool hasPermissionForSave = HasPermissionFor(AppSecurity.APP_USERS_SETPERMISSION_ + WebApplicationInfo.Id.ToString());

            this.lnkGuardar.Visible = hasPermissionForSave;
            actionButtons.Where(a => a.ID == "guardarButton").Single().Visible = hasPermissionForSave;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Agregar el resetear password en esta pantalla como una acción
            try
            {
                if (!this.IsPostBack)
                {
                    if (this.Request.QueryString["UserName"] != null &&
                        this.Request.QueryString["applicationId"] != null
                        )
                    {
                        WebApplicationInfo = WebServiceHelper.GetApplicationById(Convert.ToInt32(this.Request.QueryString["applicationId"]));                        
                        AdUser = WebServiceHelper.GetUser(WebApplicationInfo.Id, this.GetSingleContextCompany().Id, this.Request.QueryString["UserName"]);                        

                        HasPermissionToSeeMe(AppSecurity.APP_USERS_VIEWPERMISSION_ + WebApplicationInfo.Id.ToString());

                        Bind();

                    }
                    else
                    {
                        ExceptionManager.Instance.ShowWarning("La página fue accedida con parametros incorrectos, por favor vuelva a intentar la operación");
                    }
                }

                HasPermissionToSeeMe(AppSecurity.APP_USERS_VIEWPERMISSION_ + WebApplicationInfo.Id.ToString());
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Bind()
        {
            this.txtAplicacion.Text = WebApplicationInfo.Name;
            lblUserName.Text = AdUser.UserName;          

            if (AdUser.Id != 0)
            {
                var rolesForUser = AdUser.Roles;

                this.Grid.DataSource = rolesForUser;
                this.Grid.DataBind();                                
            }
        }

        private void SetData()
        {
            AdUser.ApplicationId = WebApplicationInfo.Id;
            AdUser.CompanyId = this.GetSingleContextCompany().Id;
            AdUser.UserName = this.lblUserName.Text;

            //Obtengo los valores checkeados
            List<int> selectedRowsIds = UIHelper.GetSelectedRowIds(this.hidCheckedRows.Value);

            foreach (var userRole in AdUser.Roles)
            {
                if (selectedRowsIds.Contains(userRole.Id))
                {
                    userRole.IsIncluded = true;
                }
                else
                {
                    userRole.IsIncluded = false;
                }
            }

            this.hidCheckedRows.Value = string.Empty;
        }

        private const int rowOperaciones = 3;
        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    RoleIncluded role = (RoleIncluded)e.Row.DataItem;

                    CheckBox chkSelect = (CheckBox)e.Row.Cells[0].FindControl("chkSelectRow");
                    chkSelect.Checked = role.IsIncluded;
                    if (role.IsIncluded)
                    {
                        this.hidCheckedRows.Value += string.Format("#{0}#", role.Id);
                    }

                    LinkButton lnkRowVerOperaciones = (LinkButton)e.Row.Cells[rowOperaciones].FindControl("lnkRowVerOperaciones");
                    lnkRowVerOperaciones.CommandArgument = e.Row.RowIndex.ToString();                    
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "operaciones")
                {
                    int roleId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format("/App/RoleEdit.aspx?Id={0}&applicationId={1}", roleId, WebApplicationInfo.Id), true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Save()
        {
            this.AdUser = WebServiceHelper.SaveUser(this.AdUser);
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                SetData();
                Save();
                Bind();
                this.masterPage.ShowMessage("Los perfiles se asignaron correctamente", WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}